package com.codef.sharp.common.core.interceptor;

import cn.hutool.core.util.StrUtil;
import com.codef.sharp.common.core.constant.AuthConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * feign请求拦截器，设置头部信息
 * @author zhanrf
 * @date 2022/1/21 14:14
 */
@Component
@ConditionalOnClass({RequestInterceptor.class})
public class FeignInterceptor implements RequestInterceptor{

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String authorization = request.getHeader(AuthConstant.HEADER);
        if (StrUtil.isNotBlank(authorization)) {
            requestTemplate.header(AuthConstant.HEADER, authorization);
        }
    }
}
